package com.hu.gateway.config;

import com.auth0.jwt.JWT;
import com.hu.common.common.HttpStatus;
import com.hu.common.pojo.User;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    /**
     *
     * @param exchange 上下文：理解为当次请求
     * @param chain 过滤器链，控制是否放行给下一个过滤器
     * @return 返回值是Mono类型
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取请求参数
        HttpHeaders headers = exchange.getRequest().getHeaders();
        List<String> token = headers.get("token");
        System.out.println("token=====================>" + token);



        // 3.校验
//        if (token) {
//            String userId = JWT.decode(token).getAudience().get(0);
//
//        }
        // 4.拦截
//         exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
//         return exchange.getResponse().setComplete();

        return chain.filter(exchange);
    }

    // 配置过滤器的顺序
    @Override
    public int getOrder() {
        return 0;
    }


    public static User getCurrentUser() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            System.out.println("token-------->"+request.getHeader("token"));
            String token = request.getHeader("token");
        } catch (Exception e) {
            return null;
        }
        return null;
    }
}
